import { PermissionData } from '@/api/userAndAuth';
import { usePermissionStore } from '@/store/modules/permission';
import { isArray } from 'lodash';

interface PermissionParam {
  objectId: string;
  objectType: string;
  role: string | string[];
}

export function usePermission() {
  const permissionStore = usePermissionStore();
  function hasPermission(value: PermissionParam | PermissionParam[]) {
    const newValue = isArray(value) ? value : [value];
    const hasPerm = permissionStore.getPermissionList.some((item: PermissionData) =>
      // @ts-ignore
      newValue.some((val: PermissionParam) => {
        const currentRoles = isArray(val.role) ? val.role : [val.role];
        return (
          item.objectId === val.objectId &&
          item.objectType === val.objectType &&
          item.targetUser === permissionStore.getUserInfo.userId &&
          currentRoles.includes(JSON.parse(item.userAttribute as string).role)
        );
      }),
    );
    return hasPerm;
  }
  return { hasPermission };
}
